home *** CD-ROM | disk | FTP | other *** search
/ Game.EXE 2001 January / Game.EXE_01_2001.iso / demos / Blade of Darkness / data1.cab / Program_Executable_Files / Lib / PythonLib / profile.py < prev    next >
Encoding:
Python Source  |  2000-11-16  |  21.6 KB  |  655 lines

  1. #! /usr/bin/env python
  2. #
  3. # Class for profiling python code. rev 1.0  6/2/94
  4. #
  5. # Based on prior profile module by Sjoerd Mullender...
  6. #   which was hacked somewhat by: Guido van Rossum
  7. #
  8. # See profile.doc for more information
  9.  
  10.  
  11. # Copyright 1994, by InfoSeek Corporation, all rights reserved.
  12. # Written by James Roskind
  13. # Permission to use, copy, modify, and distribute this Python software
  14. # and its associated documentation for any purpose (subject to the
  15. # restriction in the following sentence) without fee is hereby granted,
  16. # provided that the above copyright notice appears in all copies, and
  17. # that both that copyright notice and this permission notice appear in
  18. # supporting documentation, and that the name of InfoSeek not be used in
  19. # advertising or publicity pertaining to distribution of the software
  20. # without specific, written prior permission.  This permission is
  21. # explicitly restricted to the copying and modification of the software
  22. # to remain in Python, compiled Python, or other languages (such as C)
  23. # wherein the modified or derived code is exclusively imported into a
  24. # Python module.
  25. # INFOSEEK CORPORATION DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS
  26. # SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND
  27. # FITNESS. IN NO EVENT SHALL INFOSEEK CORPORATION BE LIABLE FOR ANY
  28. # SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER
  29. # RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF
  30. # CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
  31. # CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
  32.  
  33.  
  34.  
  35. import sys
  36. import os
  37. import time
  38. import string
  39. import marshal
  40.  
  41.  
  42. # Global variables
  43. func_norm_dict = {}
  44. func_norm_counter = 0
  45. if hasattr(os, 'getpid'):
  46.     pid_string = `os.getpid()`
  47. else:
  48.     pid_string = ''
  49.  
  50.  
  51. # Sample timer for use with 
  52. #i_count = 0
  53. #def integer_timer():
  54. #    global i_count
  55. #    i_count = i_count + 1
  56. #    return i_count
  57. #itimes = integer_timer # replace with C coded timer returning integers
  58.  
  59. #**************************************************************************
  60. # The following are the static member functions for the profiler class
  61. # Note that an instance of Profile() is *not* needed to call them.
  62. #**************************************************************************
  63.  
  64.  
  65. # simplified user interface
  66. def run(statement, *args):
  67.     prof = Profile()
  68.     try:
  69.         prof = prof.run(statement)
  70.     except SystemExit:
  71.         pass
  72.     if args:
  73.         prof.dump_stats(args[0])
  74.     else:
  75.         return prof.print_stats()
  76.  
  77. # print help
  78. def help():
  79.     for dirname in sys.path:
  80.         fullname = os.path.join(dirname, 'profile.doc')
  81.         if os.path.exists(fullname):
  82.             sts = os.system('${PAGER-more} '+fullname)
  83.             if sts: print '*** Pager exit status:', sts
  84.             break
  85.     else:
  86.         print 'Sorry, can\'t find the help file "profile.doc"',
  87.         print 'along the Python search path'
  88.  
  89.  
  90. #**************************************************************************
  91. # class Profile documentation:
  92. #**************************************************************************
  93. # self.cur is always a tuple.  Each such tuple corresponds to a stack
  94. # frame that is currently active (self.cur[-2]).  The following are the
  95. # definitions of its members.  We use this external "parallel stack" to
  96. # avoid contaminating the program that we are profiling. (old profiler
  97. # used to write into the frames local dictionary!!) Derived classes
  98. # can change the definition of some entries, as long as they leave
  99. # [-2:] intact.
  100. #
  101. # [ 0] = Time that needs to be charged to the parent frame's function.  It is
  102. #        used so that a function call will not have to access the timing data
  103. #        for the parents frame.
  104. # [ 1] = Total time spent in this frame's function, excluding time in
  105. #        subfunctions
  106. # [ 2] = Cumulative time spent in this frame's function, including time in
  107. #        all subfunctions to this frame.
  108. # [-3] = Name of the function that corresonds to this frame.  
  109. # [-2] = Actual frame that we correspond to (used to sync exception handling)
  110. # [-1] = Our parent 6-tuple (corresonds to frame.f_back)
  111. #**************************************************************************
  112. # Timing data for each function is stored as a 5-tuple in the dictionary
  113. # self.timings[].  The index is always the name stored in self.cur[4].
  114. # The following are the definitions of the members:
  115. #
  116. # [0] = The number of times this function was called, not counting direct
  117. #       or indirect recursion,
  118. # [1] = Number of times this function appears on the stack, minus one
  119. # [2] = Total time spent internal to this function
  120. # [3] = Cumulative time that this function was present on the stack.  In
  121. #       non-recursive functions, this is the total execution time from start
  122. #       to finish of each invocation of a function, including time spent in
  123. #       all subfunctions.
  124. # [5] = A dictionary indicating for each function name, the number of times
  125. #       it was called by us.
  126. #**************************************************************************
  127. # We produce function names via a repr() call on the f_code object during
  128. # profiling. This save a *lot* of CPU time.  This results in a string that
  129. # always looks like:
  130. #   <code object main at 87090, file "/a/lib/python-local/myfib.py", line 76>
  131. # After we "normalize it, it is a tuple of filename, line, function-name.
  132. # We wait till we are done profiling to do the normalization.
  133. # *IF* this repr format changes, then only the normalization routine should
  134. # need to be fixed.
  135. #**************************************************************************
  136. class Profile:
  137.  
  138.     def __init__(self, timer=None):
  139.         self.timings = {}
  140.         self.cur = None
  141.         self.cmd = ""
  142.  
  143.         self.dispatch = {  \
  144.               'call'     : self.trace_dispatch_call, \
  145.               'return'   : self.trace_dispatch_return, \
  146.               'exception': self.trace_dispatch_exception, \
  147.               }
  148.  
  149.         if not timer:
  150.             if os.name == 'mac':
  151.                 import MacOS
  152.                 self.timer = MacOS.GetTicks
  153.                 self.dispatcher = self.trace_dispatch_mac
  154.                 self.get_time = self.get_time_mac
  155.             elif hasattr(time, 'clock'):
  156.                 self.timer = time.clock
  157.                 self.dispatcher = self.trace_dispatch_i
  158.             elif hasattr(os, 'times'):
  159.                 self.timer = os.times
  160.                 self.dispatcher = self.trace_dispatch
  161.             else:
  162.                 self.timer = time.time
  163.                 self.dispatcher = self.trace_dispatch_i
  164.         else:
  165.             self.timer = timer
  166.             t = self.timer() # test out timer function
  167.             try:
  168.                 if len(t) == 2:
  169.                     self.dispatcher = self.trace_dispatch
  170.                 else:
  171.                     self.dispatcher = self.trace_dispatch_l
  172.             except TypeError:
  173.                 self.dispatcher = self.trace_dispatch_i
  174.         self.t = self.get_time()
  175.         self.simulate_call('profiler')
  176.  
  177.  
  178.     def get_time(self): # slow simulation of method to acquire time
  179.         t = self.timer()
  180.         if type(t) == type(()) or type(t) == type([]):
  181.             t = reduce(lambda x,y: x+y, t, 0)
  182.         return t
  183.         
  184.     def get_time_mac(self):
  185.         return self.timer()/60.0
  186.  
  187.     # Heavily optimized dispatch routine for os.times() timer
  188.  
  189.     def trace_dispatch(self, frame, event, arg):
  190.         t = self.timer()
  191.         t = t[0] + t[1] - self.t        # No Calibration constant
  192.         # t = t[0] + t[1] - self.t - .00053 # Calibration constant
  193.  
  194.         if self.dispatch[event](frame,t):
  195.             t = self.timer()
  196.             self.t = t[0] + t[1]
  197.         else:
  198.             r = self.timer()
  199.             self.t = r[0] + r[1] - t # put back unrecorded delta
  200.         return
  201.  
  202.  
  203.  
  204.     # Dispatch routine for best timer program (return = scalar integer)
  205.  
  206.     def trace_dispatch_i(self, frame, event, arg):
  207.         t = self.timer() - self.t # - 1 # Integer calibration constant
  208.         if self.dispatch[event](frame,t):
  209.             self.t = self.timer()
  210.         else:
  211.             self.t = self.timer() - t  # put back unrecorded delta
  212.         return
  213.     
  214.     # Dispatch routine for macintosh (timer returns time in ticks of 1/60th second)
  215.  
  216.     def trace_dispatch_mac(self, frame, event, arg):
  217.         t = self.timer()/60.0 - self.t # - 1 # Integer calibration constant
  218.         if self.dispatch[event](frame,t):
  219.             self.t = self.timer()/60.0
  220.         else:
  221.             self.t = self.timer()/60.0 - t  # put back unrecorded delta
  222.         return
  223.  
  224.  
  225.     # SLOW generic dispatch rountine for timer returning lists of numbers
  226.  
  227.     def trace_dispatch_l(self, frame, event, arg):
  228.         t = self.get_time() - self.t
  229.  
  230.         if self.dispatch[event](frame,t):
  231.             self.t = self.get_time()
  232.         else:
  233.             self.t = self.get_time()-t # put back unrecorded delta
  234.         return
  235.  
  236.  
  237.     def trace_dispatch_exception(self, frame, t):
  238.         rt, rtt, rct, rfn, rframe, rcur = self.cur
  239.         if (not rframe is frame) and rcur:
  240.             return self.trace_dispatch_return(rframe, t)
  241.         return 0
  242.  
  243.  
  244.     def trace_dispatch_call(self, frame, t):
  245.         fn = `frame.f_code` 
  246.  
  247.         # The following should be about the best approach, but
  248.         # we would need a function that maps from id() back to
  249.         # the actual code object.  
  250.         #     fn = id(frame.f_code)
  251.         # Note we would really use our own function, which would
  252.         # return the code address, *and* bump the ref count.  We
  253.         # would then fix up the normalize function to do the
  254.         # actualy repr(fn) call.
  255.  
  256.         # The following is an interesting alternative
  257.         # It doesn't do as good a job, and it doesn't run as
  258.         # fast 'cause repr() is written in C, and this is Python.
  259.         #fcode = frame.f_code
  260.         #code = fcode.co_code
  261.         #if ord(code[0]) == 127: #  == SET_LINENO
  262.         #    # see "opcode.h" in the Python source
  263.         #    fn = (fcode.co_filename, ord(code[1]) | \
  264.         #          ord(code[2]) << 8, fcode.co_name)
  265.         #else:
  266.         #    fn = (fcode.co_filename, 0, fcode.co_name)
  267.  
  268.         self.cur = (t, 0, 0, fn, frame, self.cur)
  269.         if self.timings.has_key(fn):
  270.             cc, ns, tt, ct, callers = self.timings[fn]
  271.             self.timings[fn] = cc, ns + 1, tt, ct, callers
  272.         else:
  273.             self.timings[fn] = 0, 0, 0, 0, {}
  274.         return 1
  275.  
  276.     def trace_dispatch_return(self, frame, t):
  277.         # if not frame is self.cur[-2]: raise "Bad return", self.cur[3]
  278.  
  279.         # Prefix "r" means part of the Returning or exiting frame
  280.         # Prefix "p" means part of the Previous or older frame
  281.  
  282.         rt, rtt, rct, rfn, frame, rcur = self.cur
  283.         rtt = rtt + t
  284.         sft = rtt + rct
  285.  
  286.         pt, ptt, pct, pfn, pframe, pcur = rcur
  287.         self.cur = pt, ptt+rt, pct+sft, pfn, pframe, pcur
  288.  
  289.         cc, ns, tt, ct, callers = self.timings[rfn]
  290.         if not ns:
  291.             ct = ct + sft
  292.             cc = cc + 1
  293.         if callers.has_key(pfn):
  294.             callers[pfn] = callers[pfn] + 1  # hack: gather more
  295.             # stats such as the amount of time added to ct courtesy
  296.             # of this specific call, and the contribution to cc
  297.             # courtesy of this call.
  298.         else:
  299.             callers[pfn] = 1
  300.         self.timings[rfn] = cc, ns - 1, tt+rtt, ct, callers
  301.  
  302.         return 1
  303.  
  304.     # The next few function play with self.cmd. By carefully preloading
  305.     # our paralell stack, we can force the profiled result to include
  306.     # an arbitrary string as the name of the calling function.
  307.     # We use self.cmd as that string, and the resulting stats look
  308.     # very nice :-).
  309.  
  310.     def set_cmd(self, cmd):
  311.         if self.cur[-1]: return   # already set
  312.         self.cmd = cmd
  313.         self.simulate_call(cmd)
  314.  
  315.     class fake_code:
  316.         def __init__(self, filename, line, name):
  317.             self.co_filename = filename
  318.             self.co_line = line
  319.             self.co_name = name
  320.             self.co_code = '\0'  # anything but 127
  321.  
  322.         def __repr__(self):
  323.             return (self.co_filename, self.co_line, self.co_name)
  324.  
  325.     class fake_frame:
  326.         def __init__(self, code, prior):
  327.             self.f_code = code
  328.             self.f_back = prior
  329.             
  330.     def simulate_call(self, name):
  331.         code = self.fake_code('profile', 0, name)
  332.         if self.cur:
  333.             pframe = self.cur[-2]
  334.         else:
  335.             pframe = None
  336.         frame = self.fake_frame(code, pframe)
  337.         a = self.dispatch['call'](frame, 0)
  338.         return
  339.  
  340.     # collect stats from pending stack, including getting final
  341.     # timings for self.cmd frame.
  342.     
  343.     def simulate_cmd_complete(self):   
  344.         t = self.get_time() - self.t
  345.         while self.cur[-1]:
  346.             # We *can* cause assertion errors here if
  347.             # dispatch_trace_return checks for a frame match!
  348.             a = self.dispatch['return'](self.cur[-2], t)
  349.             t = 0
  350.         self.t = self.get_time() - t
  351.  
  352.     
  353.     def print_stats(self):
  354.         import pstats
  355.         pstats.Stats(self).strip_dirs().sort_stats(-1). \
  356.               print_stats()
  357.  
  358.     def dump_stats(self, file):
  359.         f = open(file, 'wb')
  360.         self.create_stats()
  361.         marshal.dump(self.stats, f)
  362.         f.close()
  363.  
  364.     def create_stats(self):
  365.         self.simulate_cmd_complete()
  366.         self.snapshot_stats()
  367.  
  368.     def snapshot_stats(self):
  369.         self.stats = {}
  370.         for func in self.timings.keys():
  371.             cc, ns, tt, ct, callers = self.timings[func]
  372.             nor_func = self.func_normalize(func)
  373.             nor_callers = {}
  374.             nc = 0
  375.             for func_caller in callers.keys():
  376.                 nor_callers[self.func_normalize(func_caller)]=\
  377.                       callers[func_caller]
  378.                 nc = nc + callers[func_caller]
  379.             self.stats[nor_func] = cc, nc, tt, ct, nor_callers
  380.  
  381.  
  382.     # Override the following function if you can figure out
  383.     # a better name for the binary f_code entries.  I just normalize
  384.     # them sequentially in a dictionary.  It would be nice if we could
  385.     # *really* see the name of the underlying C code :-).  Sometimes
  386.     #  you can figure out what-is-what by looking at caller and callee
  387.     # lists (and knowing what your python code does).
  388.     
  389.     def func_normalize(self, func_name):
  390.         global func_norm_dict
  391.         global func_norm_counter
  392.         global func_sequence_num
  393.  
  394.         if func_norm_dict.has_key(func_name):
  395.             return func_norm_dict[func_name]
  396.         if type(func_name) == type(""):
  397.             long_name = string.split(func_name)
  398.             file_name = long_name[-3][1:-2]
  399.             func = long_name[2]
  400.             lineno = long_name[-1][:-1]
  401.             if '?' == func:   # Until I find out how to may 'em...
  402.                 file_name = 'python'
  403.                 func_norm_counter = func_norm_counter + 1
  404.                 func = pid_string + ".C." + `func_norm_counter`
  405.             result =  file_name ,  string.atoi(lineno) , func
  406.         else:
  407.             result = func_name
  408.         func_norm_dict[func_name] = result
  409.         return result
  410.  
  411.  
  412.     # The following two methods can be called by clients to use
  413.     # a profiler to profile a statement, given as a string.
  414.     
  415.     def run(self, cmd):
  416.         import __main__
  417.         dict = __main__.__dict__
  418.         return self.runctx(cmd, dict, dict)
  419.     
  420.     def runctx(self, cmd, globals, locals):
  421.         self.set_cmd(cmd)
  422.         sys.setprofile(self.dispatcher)
  423.         try:
  424.             exec cmd in globals, locals
  425.         finally:
  426.             sys.setprofile(None)
  427.         return self
  428.  
  429.     # This method is more useful to profile a single function call.
  430.     def runcall(self, func, *args):
  431.         self.set_cmd(`func`)
  432.         sys.setprofile(self.dispatcher)
  433.         try:
  434.             return apply(func, args)
  435.         finally:
  436.             sys.setprofile(None)
  437.  
  438.  
  439.     #******************************************************************
  440.     # The following calculates the overhead for using a profiler.  The
  441.     # problem is that it takes a fair amount of time for the profiler
  442.     # to stop the stopwatch (from the time it recieves an event).
  443.     # Similarly, there is a delay from the time that the profiler
  444.     # re-starts the stopwatch before the user's code really gets to
  445.     # continue.  The following code tries to measure the difference on
  446.     # a per-event basis. The result can the be placed in the
  447.     # Profile.dispatch_event() routine for the given platform.  Note
  448.     # that this difference is only significant if there are a lot of
  449.     # events, and relatively little user code per event.  For example,
  450.     # code with small functions will typically benefit from having the
  451.     # profiler calibrated for the current platform.  This *could* be
  452.     # done on the fly during init() time, but it is not worth the
  453.     # effort.  Also note that if too large a value specified, then
  454.     # execution time on some functions will actually appear as a
  455.     # negative number.  It is *normal* for some functions (with very
  456.     # low call counts) to have such negative stats, even if the
  457.     # calibration figure is "correct." 
  458.     #
  459.     # One alternative to profile-time calibration adjustments (i.e.,
  460.     # adding in the magic little delta during each event) is to track
  461.     # more carefully the number of events (and cumulatively, the number
  462.     # of events during sub functions) that are seen.  If this were
  463.     # done, then the arithmetic could be done after the fact (i.e., at
  464.     # display time).  Currintly, we track only call/return events.
  465.     # These values can be deduced by examining the callees and callers
  466.     # vectors for each functions.  Hence we *can* almost correct the
  467.     # internal time figure at print time (note that we currently don't
  468.     # track exception event processing counts).  Unfortunately, there
  469.     # is currently no similar information for cumulative sub-function
  470.     # time.  It would not be hard to "get all this info" at profiler
  471.     # time.  Specifically, we would have to extend the tuples to keep
  472.     # counts of this in each frame, and then extend the defs of timing
  473.     # tuples to include the significant two figures. I'm a bit fearful
  474.     # that this additional feature will slow the heavily optimized
  475.     # event/time ratio (i.e., the profiler would run slower, fur a very
  476.     # low "value added" feature.) 
  477.     #
  478.     # Plugging in the calibration constant doesn't slow down the
  479.     # profiler very much, and the accuracy goes way up.
  480.     #**************************************************************
  481.     
  482.     def calibrate(self, m):
  483.         # Modified by Tim Peters
  484.         n = m
  485.         s = self.get_time()
  486.         while n:
  487.             self.simple()
  488.             n = n - 1
  489.         f = self.get_time()
  490.         my_simple = f - s
  491.         #print "Simple =", my_simple,
  492.  
  493.         n = m
  494.         s = self.get_time()
  495.         while n:
  496.             self.instrumented()
  497.             n = n - 1
  498.         f = self.get_time()
  499.         my_inst = f - s
  500.         # print "Instrumented =", my_inst
  501.         avg_cost = (my_inst - my_simple)/m
  502.         #print "Delta/call =", avg_cost, "(profiler fixup constant)"
  503.         return avg_cost
  504.  
  505.     # simulate a program with no profiler activity
  506.     def simple(self):
  507.         a = 1
  508.         pass
  509.  
  510.     # simulate a program with call/return event processing
  511.     def instrumented(self):
  512.         a = 1
  513.         self.profiler_simulation(a, a, a)
  514.  
  515.     # simulate an event processing activity (from user's perspective)
  516.     def profiler_simulation(self, x, y, z):  
  517.         t = self.timer()
  518.         t = t[0] + t[1]
  519.         self.ut = t
  520.  
  521.  
  522.  
  523. #****************************************************************************
  524. # OldProfile class documentation
  525. #****************************************************************************
  526. #
  527. # The following derived profiler simulates the old style profile, providing
  528. # errant results on recursive functions. The reason for the usefulnes of this
  529. # profiler is that it runs faster (i.e., less overhead).  It still creates
  530. # all the caller stats, and is quite useful when there is *no* recursion
  531. # in the user's code.
  532. #
  533. # This code also shows how easy it is to create a modified profiler.
  534. #****************************************************************************
  535. class OldProfile(Profile):
  536.     def trace_dispatch_exception(self, frame, t):
  537.         rt, rtt, rct, rfn, rframe, rcur = self.cur
  538.         if rcur and not rframe is frame:
  539.             return self.trace_dispatch_return(rframe, t)
  540.         return 0
  541.  
  542.     def trace_dispatch_call(self, frame, t):
  543.         fn = `frame.f_code`
  544.         
  545.         self.cur = (t, 0, 0, fn, frame, self.cur)
  546.         if self.timings.has_key(fn):
  547.             tt, ct, callers = self.timings[fn]
  548.             self.timings[fn] = tt, ct, callers
  549.         else:
  550.             self.timings[fn] = 0, 0, {}
  551.         return 1
  552.  
  553.     def trace_dispatch_return(self, frame, t):
  554.         rt, rtt, rct, rfn, frame, rcur = self.cur
  555.         rtt = rtt + t
  556.         sft = rtt + rct
  557.  
  558.         pt, ptt, pct, pfn, pframe, pcur = rcur
  559.         self.cur = pt, ptt+rt, pct+sft, pfn, pframe, pcur
  560.  
  561.         tt, ct, callers = self.timings[rfn]
  562.         if callers.has_key(pfn):
  563.             callers[pfn] = callers[pfn] + 1
  564.         else:
  565.             callers[pfn] = 1
  566.         self.timings[rfn] = tt+rtt, ct + sft, callers
  567.  
  568.         return 1
  569.  
  570.  
  571.     def snapshot_stats(self):
  572.         self.stats = {}
  573.         for func in self.timings.keys():
  574.             tt, ct, callers = self.timings[func]
  575.             nor_func = self.func_normalize(func)
  576.             nor_callers = {}
  577.             nc = 0
  578.             for func_caller in callers.keys():
  579.                 nor_callers[self.func_normalize(func_caller)]=\
  580.                       callers[func_caller]
  581.                 nc = nc + callers[func_caller]
  582.             self.stats[nor_func] = nc, nc, tt, ct, nor_callers
  583.  
  584.         
  585.  
  586. #****************************************************************************
  587. # HotProfile class documentation
  588. #****************************************************************************
  589. #
  590. # This profiler is the fastest derived profile example.  It does not
  591. # calculate caller-callee relationships, and does not calculate cumulative
  592. # time under a function.  It only calculates time spent in a function, so
  593. # it runs very quickly (re: very low overhead)
  594. #****************************************************************************
  595. class HotProfile(Profile):
  596.     def trace_dispatch_exception(self, frame, t):
  597.         rt, rtt, rfn, rframe, rcur = self.cur
  598.         if rcur and not rframe is frame:
  599.             return self.trace_dispatch_return(rframe, t)
  600.         return 0
  601.  
  602.     def trace_dispatch_call(self, frame, t):
  603.         self.cur = (t, 0, frame, self.cur)
  604.         return 1
  605.  
  606.     def trace_dispatch_return(self, frame, t):
  607.         rt, rtt, frame, rcur = self.cur
  608.  
  609.         rfn = `frame.f_code`
  610.  
  611.         pt, ptt, pframe, pcur = rcur
  612.         self.cur = pt, ptt+rt, pframe, pcur
  613.  
  614.         if self.timings.has_key(rfn):
  615.             nc, tt = self.timings[rfn]
  616.             self.timings[rfn] = nc + 1, rt + rtt + tt
  617.         else:
  618.             self.timings[rfn] =      1, rt + rtt
  619.  
  620.         return 1
  621.  
  622.  
  623.     def snapshot_stats(self):
  624.         self.stats = {}
  625.         for func in self.timings.keys():
  626.             nc, tt = self.timings[func]
  627.             nor_func = self.func_normalize(func)
  628.             self.stats[nor_func] = nc, nc, tt, 0, {}
  629.  
  630.         
  631.  
  632. #****************************************************************************
  633. def Stats(*args):
  634.     print 'Report generating functions are in the "pstats" module\a'
  635.  
  636.  
  637. # When invoked as main program, invoke the profiler on a script
  638. if __name__ == '__main__':
  639.     import sys
  640.     import os
  641.     if not sys.argv[1:]:
  642.         print "usage: profile.py scriptfile [arg] ..."
  643.         sys.exit(2)
  644.  
  645.     filename = sys.argv[1]    # Get script filename
  646.  
  647.     del sys.argv[0]        # Hide "profile.py" from argument list
  648.  
  649.     # Insert script directory in front of module search path
  650.     sys.path.insert(0, os.path.dirname(filename))
  651.  
  652.     run('execfile(' + `filename` + ')')
  653.